<template>

  <avue-crud ref="gameListRef" :table-loading="tableLoading" v-model="form" :option="option" @refresh-change="getList"
    @row-save="rowSave" @row-update="rowUpdate" @row-del="rowDel" :data="data" :page="page" @size-change="sizeChange"
    @current-change="currentChange" @search-change="searchChange" @search-reset="searchReset">
    <template #header="{ row, index, size }">
      <div>
        <el-collapse v-model="accordionExpanded">
          <el-collapse-item name="1">
            <template #title>
              <div>
                📊 分类排序修改
              </div>
            </template>
            <draggable v-loading="loading" v-model="spines" :options="{ group: 'spines', animation: 200 }"
              @start="handleDragStart" @end="handleDragEnd">
              <template #item="{ element }">
                <div :key="element.id" class="spine-item draggable-item">
                  <i class="el-icon-rank"></i> <!-- Draggable icon added here -->
                  {{ element.label }}
                </div>
              </template>
            </draggable>
          </el-collapse-item>
        </el-collapse>
      </div>
    </template>
  </avue-crud>
</template>
<!--  :upload-preview="uploadPreview" -->
<!-- :upload-before="fileTest" :upload-after="uploadAfter" -->
<!-- :upload-before="fileTest" -->
<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from "vue";
import gameList from "@/options/gameList";
import { ElMessageBox, ElMessage } from "element-plus";
import { getGameList, delGame, addGame, editGame, getGameTypeSort, setGameTypeSort } from "@/apis/admin";
import aws_cfg from "@/utils/aws";
import draggable from 'vuedraggable';
import { ElCollapse, ElCollapseItem } from 'element-plus';

const option = gameList;
const data = ref([]);
const form = ref({});
const tableLoading = ref(false);
const page = reactive({
  total: 0,
  searchInfo: {},
  currentPage: 1,
  pageSize: 10,
});

const spines = ref([
  { id: 1, label: "loding..." },
]);

const accordionExpanded = ref([]);
const loading = ref(false);

const handleDragStart = (event) => {
  console.log('drag start', event);
};

const handleDragEnd = (event) => {
  console.log('drag end', spines.value);
  loading.value = true;
  // 将spines.value.id 转换为数组
  const ids = spines.value.map(item => item.id);
  setGameTypeSort.post("", {
    list: ids,
  }).then((res) => {
    if (res.code == 200) {
      loading.value = false;
    }
  }).catch(err => {
    // 提示错误
    ElMessage.error("保存失败!");
    loading.value = false;
  });

};

const toggleAccordion = () => {
  if (accordionExpanded.value.length) {
    accordionExpanded.value = [];
  } else {
    accordionExpanded.value = ['1'];
  }
};

const sizeChange = (val) => {
  page.pageSize = val;
  getList();
};
const currentChange = (val) => {
  page.currentPage = val;
  getList();
};
const searchChange = (form, done) => {
  page.searchInfo = form;
  page.currentPage = 1;
  getList();
  done();
};
const searchReset = () => {
  page.searchInfo = {};
  page.currentPage = 1;
  getList();
};
const rowSave = async (row, done, loading) => {
  const res = await addGame.post("", { ...row, isRecommend: 0 });
  if (res.code == 200) {
    done();
    ElMessage.success("添加成功!");
    getList();
  } else {
    ElMessage.error("添加失败!");
  }
};
const rowDel = (row, index, done) => {
  ElMessageBox.confirm("此操作将永久删除该游戏, 是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delGame.post("", { id: row.id }).then((res) => {
      if (res.code == 200) {
        ElMessage({
          message: "已删除",
          type: "success",
        });
        getList();
      }
    });
  });
};
const rowUpdate = async (row, index, done, loading) => {
  const res = await editGame.post("", row);
  if (res.code == 200) {
    done();
    ElMessage.success("编辑成功!");
    getList();
  } else {
    ElMessage.error("编辑失败!");
  }
};

const getList = () => {
  tableLoading.value = true;

  getGameList
    .post("", {
      searchInfo: page.searchInfo,
      page: page.currentPage,
      pageSize: page.pageSize,
      orderKey: "created_at",
      orderType: "desc",
    })
    .then((res) => {
      if (res.code == 200) {
        page.total = res.data.total;
        data.value = res.data.list || [];
      }
      tableLoading.value = false;
    });
};
const getSoltList = () => {
  tableLoading.value = true;
  getGameTypeSort.post("", {
    list: [1, 2, 3, 4, 5],
  }).then((res) => {
    if (res.code == 200) {
      let list = res.data.list.length >= 5 ? res.data.list : [1, 2, 3, 4, 5];
      // list只是数字，需要对应label  [1,2,3,4,5]
      let temp = [
        { id: 1, label: "Slot" },
        { id: 2, label: "Popular" },
        { id: 3, label: "Live" },
        { id: 4, label: "Mini" },
        { id: 5, label: "Spin" },
      ]

      spines.value = list.map(id => temp.find(item => item.id === id));
      tableLoading.value = false;
    }
  });
}

onMounted(() => {
  getList();
  getSoltList();
});

onUnmounted(() => {
});

const fileTest = async (file, done, loading) => {
  console.log('test ==== ', 'file', file, 'done', done, 'loading', loading)
  // let data = await aws_cfg.uploadToS3(file)
  console.log('file end')
  // done()
  return false;
}
const uploadAfter = (res, done, loading, column) => {
  console.log('uploadAfter::', res, column)
  done()
}
const uploadFile = () => {
  console.log('uploadFile:::')
}
const uploadPreview = () => {
  console.log('uploadPreview')
}
</script>

<style scoped>
.draggable-item {
  padding: 10px;
  margin: 5px 0;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.draggable-item:hover {
  background-color: #e9e9e9;
}

.accordion-toggle {
  cursor: pointer;
  transition: color 0.3s ease;
}

.accordion-toggle:hover {
  color: #007bff;
}
</style>
